﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Web.UI;
using UMC.Web;
using UMC.Wiki.Entities;

namespace UMC.Wiki.Activities
{

    class SubjectUIDataActivity : WebActivity
    {
        bool Subject(String model, UISection ui, Subject sub, Project project, int isEditer)
        {
            var webr = UMC.Web.WebResource.Instance();
            var user = this.Context.Token.Identity();
            var idReader = DataFactory.Instance().ProjectReader(this.Context.Token.UserId.Value, project.Id.Value) != null;
            if (project != null)
            {
                UIIconNameDesc uIIconNameDesc = new UIIconNameDesc(new UIIconNameDesc.Item(webr.ImageResolve(this.Context.Request.Url, project.Id.Value, "1", 4, Utility.TimeSpan(project.ModifiedTime ?? DateTime.Now).ToString()), project.Caption, project.Description ?? "未写描述")
                .Click(new UIClick(model, "ProjectUI", project.Id.ToString()))
                );
                if (idReader)
                {
                    uIIconNameDesc.Button("已订阅", null, 0x25b864);
                }
                else
                {
                    uIIconNameDesc.Button(SubjectAttentionActivity.Attention(this.Context, sub.project_id.Value, out var isIsAttention), new Web.UIClick(model, "Attention", project.Id.ToString()), isIsAttention ? 0x25b864 : 0xe67979);
                    if (isIsAttention == false)
                    {
                        uIIconNameDesc.Style.Fixed();
                    }
                }
                uIIconNameDesc.Style.Name("desc", new UIStyle().Color(0x999)).Name("name", new UIStyle().Bold());

                uIIconNameDesc.Style.Name("border", "none");

                ui.Title.Name("text", project.Caption);
                ui.Title.Name("Keywords", sub.Keywords);
                ui.Title.Name("Description", sub.Description);

                ui.Title.Name("src", webr.ImageResolve(this.Context.Request.Url, project.Id.Value, "1", 4));



                ui.Add(uIIconNameDesc);
                if (user.IsAuthenticated)
                {
                    if (isEditer > -1)
                    {
                        DataFactory.Instance().Put(new ProjectAccess
                        {
                            CreationTime = DateTime.Now,
                            Times = 1,
                            LastAccessTime = DateTime.Now,
                            sub_id = sub.Id,
                            Alias = user.Alias,
                            user_id = user.Id
                        });
                    }
                    var ax = DataFactory.Instance().Attention(sub.user_id.Value) ?? new Attention { Id = sub.user_id.Value };
                    DataFactory.Instance().Put(new Attention
                    {
                        Id = ax.Id,
                        SubjectViewTotal = (ax.SubjectViewTotal ?? 0) + 1
                    });

                }
                DataFactory.Instance().Put(new Project
                {
                    Id = project.Id,
                    ViewTotal = (project.ViewTotal ?? 0) + 1
                });
                DataFactory.Instance().Put(new Subject
                {
                    Look = (sub.Look ?? 0) + 1,
                    Id = sub.Id
                });
            }

            var conent = DataFactory.Instance().Content(sub.Id.Value) ?? new SubjectContent();

            var cateData = new UMC.Web.WebMeta().Put("icon", "\uf02c", "name", sub.Poster).Put("look", (sub.Look ?? 0) + "").Put("Reply", (sub.Reply ?? 0) + "");

            var footer2 = new UIButton(cateData);
            footer2.Title("{icon}  {name} | 阅读({look}) | 评论({Reply})");

            footer2.Style.Color(0x999).Size(14).Name("icon", new UIStyle().Font("wdk"));
            var status = project.Status ?? 0;
            if (project != null && isEditer > 0)
            {
                ui.AddCells(Utility.ContentCells(conent)); ;
                ui.Title.Name("Editer", "OK");
                if (this.Context.Request.IsApp)
                {
                    footer2.Button(new UIEventText("编辑图文").Style(new UIStyle().Color(0x3F51B5).Name("border", "none")).Click(new UIClick(model, "EditUI", sub.Id.ToString())));
                }


            }
            else if ((sub.Visible ?? 0) == 0 && this.Context.Request.IsCashier == false)
            {
                if (project.ReaderPrice > 0)
                {
                    if (idReader == false)//DataFactory.Instance().ProjectReader(this.Context.Token.UserId.Value, project.Id.Value) == null)
                    {
                        var cells = Utility.ContentCells(conent);
                        ui.AddCells(cells.AsSpan(0, cells.Length / 2).ToArray());

                        var footer = new UIButton();
                        footer.Style.AlignCenter().Height(40).Padding(0, 20, 20, 20).Name("min-width", 80);
                        var uiDesc = new UIDesc(new UMC.Web.WebMeta().Put("icon", "\uF103"));
                        uiDesc.Desc("{icon}");

                        uiDesc.Style.Align(1).Color(0xe67979).Name("icon", new UIStyle().Font("wdk").Size(15));

                        ui.Add(uiDesc);
                        if ((status & 1) == 1)
                        {

                            var best = new UIEventText('\uF023', $"只需¥{project.ReaderPrice:0.00}元解锁项目全部内容").Format("{icon} {text}")
                           .Style(new UIStyle().Radius(10).BorderColor(0xe67979).Color(0xe67979).Name("icon", new UIStyle().Font("wdk")).Size(16));

                            footer.Button(best);
                            best.Click(new UIClick(this.Context.Request.Model, "Reader", new WebMeta("Model", "Pay").Put("Id", project.Id)));
                            ui.Add(footer);
                        }
                        else
                        {

                            var best = new UIEventText('\uF023', "订阅之后才能解锁项目全部内容").Format("{icon} {text}")
                           .Style(new UIStyle().Radius(10).BorderColor(0xe67979).Color(0xe67979).Name("icon", new UIStyle().Font("wdk")).Size(16));

                            footer.Button(best);
                            ui.Add(footer);
                            best.Click(new UIClick(this.Context.Request.Model, "Reader", project.Id.Value.ToString()));
                        }
                        return true;
                    }
                    else
                    {
                        ui.AddCells(Utility.ContentCells(conent)); ;
                    }
                }
                else
                {
                    ui.AddCells(Utility.ContentCells(conent));
                    ui.Title.Name("Follow", project.Code);
                }
            }
            else
            {

                ui.AddCells(Utility.ContentCells(conent)); ;
            }
            ui.Add(footer2);

            return false;


        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var strId = this.AsyncDialog("Id", g =>
            {
                return new Web.UITextDialog() { Title = "主题" };
            });

            var subid = UMC.Data.Utility.UInt64Parse(strId);
            Subject sub = null;
            if (subid.HasValue)
            {
                sub = DataFactory.Instance().Subject(subid.Value);
            }
            Project project = null;
            ProjectItem projectItem = null;
            if (strId.IndexOf("/") > 0)
            {
                var paths = strId.Split('/');
                if (paths.Length == 3)
                {
                    project = DataFactory.Instance().Project(paths[0]);

                    if (project != null)
                    {
                        projectItem = DataFactory.Instance().ProjectItem(project.Id.Value, paths[1]);

                        if (projectItem != null)
                        {
                            sub = DataFactory.Instance().Subject(project.Id.Value, projectItem.Id.Value, paths[2]);
                        }
                    }
                }
            }


            int limit = UMC.Data.Utility.IntParse(request.SendValues?["limit"] as string, 25);
            int start = UMC.Data.Utility.IntParse(request.SendValues?["start"], 0);


            var webr = UMC.Web.WebResource.Instance();
            var user = this.Context.Token.Identity();
            var nextKey = request.SendValues?["NextKey"] ?? "Subject";



            if (sub != null && sub.project_id.HasValue && sub.project_item_id.HasValue && project == null)
            {

                project = DataFactory.Instance().Project(sub.project_id.Value);
                projectItem = DataFactory.Instance().ProjectItem(sub.project_item_id.Value);
                if (projectItem == null)
                {
                    var portfolio = DataFactory.Instance().Portfolio(sub.portfolio_id.Value);

                    if (portfolio != null)
                    {
                        projectItem = DataFactory.Instance().ProjectItem(portfolio.project_item_id.Value);
                        DataFactory.Instance().Put(new Entities.Subject { Id = sub.Id, project_item_id = portfolio.project_item_id });
                    }
                }
            }


            var ui = UISection.Create();
            var rui = ui;
            var IsSubscribe = false;
            if (nextKey == "Subject")
            {
                ui.Key = nextKey;
                if (sub == null || sub.Status == -2)
                {

                    var title = new UITitle("图文正文");
                    ui.Title = title;
                    ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "图文已关闭").Put("icon", "\uea0d")
                        , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));

                    ui.IsNext = false;

                }
                else
                {
                    ui.IsNext = true;
                    var title = new UITitle("图文正文");
                    ui.Title = title;
                    title.Name("title", sub.Title);
                    title.Name("Id", sub.Id.ToString());
                    title.Float();

                    var isEditer = -1;


                    if (project != null && projectItem != null)
                    {
                        if (String.IsNullOrEmpty(sub.Code) == false)
                        {
                            title.Name("Path", String.Format("{0}/{1}/{2}", project.Code, projectItem.Code, sub.Code));

                            if (request.IsApp)
                                title.Right('\uf141', UIClick.Click(new UIClick() { Command = "TipOff", Model = request.Model }.Send("Id", sub.Id.ToString())));


                        }

                        var member = DataFactory.Instance().ProjectMember(project.Id.Value, user.Id.Value);

                        if (member != null)
                        {
                            switch (member.AuthType)
                            {
                                case WebAuthType.Admin:
                                case WebAuthType.User:
                                    isEditer = 1;

                                    if (sub.Status > 0 && request.IsApp == false)
                                    {
                                        if ((sub.PublishTime ?? 0) + 6000 < Utility.TimeSpan())
                                        {
                                            title.Name("releaseId", sub.Id.ToString());

                                        }
                                    }
                                    break;
                                default:
                                    isEditer = 0;
                                    break;
                            }
                        }
                    }
                    var desc = new UIDesc(new WebMeta().Put("desc", sub.Title).Put("state", "未发布"));
                    desc.Style.Bold().Size(18).Name("border", "none");
                    if (sub.Status < 0)
                    {
                        desc.Desc("{desc} [{1:state:1}]");
                        desc.Style.Name("state").Color(0x999).Size(13);
                    }
                    desc.Style.Padding(55, 10, 10, 10);
                    ui.Add(desc);

                    var now = Utility.TimeSpan();
                    if ((project?.ExpireTime ?? 0) > 0 && project?.ExpireTime < now)
                    {
                        ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "项目己过期").Put("icon", "\uea0d"),
                            new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));

                        ui.IsNext = false;

                    }
                    else if (isEditer <= 0 && sub.Status < 1)
                    {
                        ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "此文档未发布，现还不能查看").Put("icon", "\uF0E6"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),

                         new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                        ui.IsNext = false;

                    }
                    else
                    {
                        ui.DisableSeparatorLine();
                        IsSubscribe = Subject(request.Model, ui, sub, project, isEditer);
                    }
                }

                if (ui.IsNext == false)
                {
                    ui.SendTo(this.Context);
                }
                if (sub.IsComment == false)
                {
                    ui.IsNext = false;
                }
                if (IsSubscribe == false)
                {
                    ui.Add(SubjectBestActivity.BSSArea(sub, request.Model, request.IsApp, ((project.Status ?? 0) & 2) == 2));
                }
                ui.StartIndex = 0;
                ui = ui.NewSection();
                start = 0;

            }

            // var status = project.Status ?? 0;

            var selectIndex = UMC.Data.Utility.IntParse(request.SendValues?["selectIndex"], 0);
            UITabFixed tabFixed = new UITabFixed();
            if (sub != null && (sub.IsComment ?? true) && ((project.Status ?? 0) & 2) == 0)
            {
                tabFixed.Add("评论", "Comments", "Comments");
            }
            tabFixed.Add("点赞", "Proposal", "Comments");
            tabFixed.Add("已读", "Access", "Comments");
            tabFixed.SelectIndex = selectIndex;

            var Keyword = request.SendValues?["Keyword"] as string ?? String.Empty;
            if (String.IsNullOrEmpty(Keyword) && selectIndex > -1)
            {
                Keyword = tabFixed.SelectValue["search"];
            }
            tabFixed.Style.Name("border", "bottom");
            ui.Add(tabFixed);
            ui.Key = "Comments";
            switch (Keyword)
            {
                case "Comments":
                    {
                        int next;

                        var cms = DataFactory.Instance().Search(new Comment { ref_id = sub.Id.Value, for_id = 0 }, false, start, out next, limit);
                        var hash = Utility.Comments(cms, request.Model, request.Url);
                        if (cms.Length == 0 && start == 0)
                        {
                            rui.IsNext = false;
                            ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "暂无评论").Put("icon", "\uF0E6"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),

                                new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                        }
                        else
                        {
                            ui.AddCells(hash.ToArray());
                            rui.IsNext = next > 0;
                        }

                    }
                    break;
                case "Access":
                    {

                        var style = new UIStyle().AlignLeft().Name("border", "none");
                        int mlimit = limit * 4;
                        int nextIndex;

                        var pas = DataFactory.Instance().Search(new ProjectAccess { sub_id = sub.Id }, start, out nextIndex, mlimit);//, dr => ids.Add(dr.user_id.Value));
                        if (pas.Length > 0)
                        {
                            var icons = new List<UIEventText>();
                            foreach (var id in pas)
                            {

                                icons.Add(new UIEventText(id.Alias).Src(webr.ImageResolve(request.Url, id.user_id.Value, "1", "4")).Click(request.IsApp ? UIClick.Pager(request.Model, "Account", new WebMeta().Put("Id", id.user_id), true) : new UIClick(request.Model, "Account", id.user_id.ToString())));

                                if (icons.Count % 4 == 0)
                                {
                                    ui.Add(new Web.UI.UIIcon().Add(icons.ToArray()));
                                    icons.Clear();
                                }

                            }
                            if (icons.Count > 0)
                            {
                                var ls = new Web.UI.UIIcon().Add(icons.ToArray());
                                ls.Style.Copy(style);
                                ui.Add(ls);
                            }
                        }
                        ui.StartIndex = nextIndex;
                        ui.IsNext = nextIndex > 0;
                        if (ui.Length == 0 && start == 0)
                            ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "暂无访问").Put("icon", "\uF0E6"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                                new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));

                        // rui.SendTo(this.Context);

                    }
                    break;
                case "Proposal":
                    {

                        var style = new UIStyle().AlignLeft().Name("border", "none");
                        int mlimit = limit * 4;
                        int mstart = start * 4;
                        var ids = new List<Guid>();

                        int m;
                        var propos = DataFactory.Instance().Search(new Proposal { ref_id = sub.Id }, mstart, out m, mlimit);
                        foreach (var c in propos)
                        {
                            if (ids.Exists(r => r == c.user_id) == false)
                            {
                                ids.Add(c.user_id.Value);
                            }
                        }
                        if (ids.Count > 0)
                        {
                            var icons = new List<UIEventText>();
                            foreach (var pr in propos)
                            {

                                icons.Add(new UIEventText(pr.Poster).Src(webr.ImageResolve(request.Url, pr.user_id.Value, "1", "4")).Click(request.IsApp ? UIClick.Pager(request.Model, "Account", new WebMeta().Put("Id", pr.user_id), true) : new UIClick(request.Model, "Account", pr.user_id.ToString())));

                                if (icons.Count % 4 == 0)
                                {
                                    ui.Add(new Web.UI.UIIcon().Add(icons.ToArray()));
                                    icons.Clear();
                                }

                            }
                            if (icons.Count > 0)
                            {
                                var ls = new Web.UI.UIIcon().Add(icons.ToArray());
                                ls.Style.Copy(style);
                                ui.Add(ls);

                            }
                        }
                        ui.IsNext = m > 0;
                        ui.StartIndex = m;
                        if (propos.Length == 0 && start == 0)
                        {
                            ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "暂无点赞").Put("icon", "\uf087"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),

                                new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                        }
                        // rui.SendTo(this.Context);

                    }
                    break;
            }
            if (IsSubscribe)
            {
                rui.SendTo(this.Context, $"{request.Model}.Reader");
            }
            else
            {
                rui.SendTo(this.Context);
            }
        }

    }
}